import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Tag, Space, Modal, Descriptions, message, Progress } from 'antd';
import { DownloadOutlined, EyeOutlined, FilePdfOutlined } from '@ant-design/icons';
import axios from 'axios';

const Reports = () => {
  const [reports, setReports] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [selectedReport, setSelectedReport] = useState(null);
  const [progressData, setProgressData] = useState({});

  useEffect(() => {
    fetchReports();
  }, []);

  const fetchReports = async () => {
    setLoading(true);
    try {
      const response = await axios.get('http://localhost:3001/api/admin/results');
      setReports(response.data.results);
    } catch (error) {
      message.error('获取报告失败：' + error.message);
    } finally {
      setLoading(false);
    }
  };

  const checkProgress = async (boxId) => {
    try {
      const response = await axios.get(`http://localhost:3001/api/tests/progress/${boxId}`);
      setProgressData(prev => ({ ...prev, [boxId]: response.data }));
    } catch (error) {
      console.error('获取进度失败:', error);
    }
  };

  const viewReport = async (record) => {
    try {
      const response = await axios.get(`http://localhost:3001/api/tests/report/${record.id}`);
      setSelectedReport(response.data.report);
      setModalVisible(true);
    } catch (error) {
      message.error('获取报告详情失败：' + error.message);
    }
  };

  const downloadPDF = async (record) => {
    try {
      const response = await axios.post('http://localhost:3001/api/upload/generate-pdf', {
        reportData: {
          patientId: record.patient_id,
          boxId: record.box_id,
          batchNumber: 'BATCH-001',
          mir193a5pLevel: record.mir_193a_5p_level || 2.5,
          confidenceScore: record.confidence_score || 95,
          analysisTime: record.analysis_time || 30,
          testDate: record.created_at,
          clinicalAccuracy: '>95%'
        }
      });

      if (response.data.success) {
        window.open(`http://localhost:3001${response.data.downloadUrl}`, '_blank');
        message.success('PDF报告生成成功！');
      }
    } catch (error) {
      message.error('生成PDF失败：' + error.message);
    }
  };

  const columns = [
    {
      title: '患者ID',
      dataIndex: 'patient_id',
      key: 'patient_id',
    },
    {
      title: '检测盒ID',
      dataIndex: 'box_id',
      key: 'box_id',
    },
    {
      title: 'miR-193a-5p水平',
      dataIndex: 'mir_193a_5p_level',
      key: 'mir_193a_5p_level',
      render: (value) => value ? value.toFixed(2) : '-',
    },
    {
      title: '置信度',
      dataIndex: 'confidence_score',
      key: 'confidence_score',
      render: (value) => value ? `${value}%` : '-',
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record) => (
        <Tag color={record.result_status === 'completed' ? 'success' : 'processing'}>
          {record.result_status === 'completed' ? '已完成' : '处理中'}
        </Tag>
      ),
    },
    {
      title: '检测时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button 
            type="text" 
            icon={<EyeOutlined />} 
            onClick={() => viewReport(record)}
          >
            查看
          </Button>
          <Button 
            type="text" 
            icon={<FilePdfOutlined />} 
            onClick={() => downloadPDF(record)}
          >
            PDF
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card 
        title="检测报告列表" 
        extra={
          <Button type="primary" onClick={fetchReports}>
            刷新
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={reports}
          loading={loading}
          rowKey="id"
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title="检测报告详情"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setModalVisible(false)}>
            关闭
          </Button>,
          <Button 
            key="download" 
            type="primary" 
            icon={<DownloadOutlined />}
            onClick={() => {
              if (selectedReport) {
                downloadPDF(selectedReport);
              }
            }}
          >
            下载PDF
          </Button>
        ]}
        width={600}
      >
        {selectedReport && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="患者ID">
              {selectedReport.patientId}
            </Descriptions.Item>
            <Descriptions.Item label="检测盒ID">
              {selectedReport.boxId}
            </Descriptions.Item>
            <Descriptions.Item label="批次号">
              {selectedReport.batchNumber}
            </Descriptions.Item>
            <Descriptions.Item label="miR-193a-5p水平">
              {selectedReport.mir193a5pLevel}
            </Descriptions.Item>
            <Descriptions.Item label="置信度">
              {selectedReport.confidenceScore}%
            </Descriptions.Item>
            <Descriptions.Item label="分析时间">
              {selectedReport.analysisTime}分钟
            </Descriptions.Item>
            <Descriptions.Item label="检测日期">
              {new Date(selectedReport.testDate).toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="临床精度">
              {selectedReport.clinicalAccuracy}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color="success">{selectedReport.status}</Tag>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default Reports;